<?php defined('SYSPATH') or die('No direct script access.');
include BASEPATH.'/ebooking/application/classes/model/ebooking/discount/strategy.php';
include BASEPATH.'/ebooking/application/classes/model/ebooking/sale/sale.php';
include BASEPATH.'/ebooking/application/classes/model/ebooking.php';
class Controller_Ebooking extends Stourweb_Controller
{
    private $type_id = 2;
    /**
     * 配置页
     */
    public function action_set_domain_name()
    {
        $fields = array('cfg_ebooking_is_open', 'cfg_ebooking_domain_name');
        $config = Model_Sysconfig::get_configs(0, $fields);

        $this->assign('config',$config);
        $this->display('stourtravel/ebooking/domain_name');
    }

    /**
     * 保存配置
     */
    public function action_ajax_save()
    {
        $cfg_ebooking_is_open = Arr::get($_POST,'cfg_ebooking_is_open');
        $cfg_ebooking_domain_name = Arr::get($_POST,'cfg_ebooking_domain_name');
        self::insertOrUpdate('cfg_ebooking_is_open',$cfg_ebooking_is_open);
        self::insertOrUpdate('cfg_ebooking_domain_name',$cfg_ebooking_domain_name);

        echo json_encode(array('status' => true));
    }

    /**
     * @param $varname
     * @param $value
     * @throws Kohana_Exception
     * 修改或插入
     */
    public function insertOrUpdate($varname, $value)
    {
        $is_exist = DB::select()->from('sysconfig')->where("varname='{$varname}'")->execute()->current();
        if($is_exist){
            DB::update('sysconfig')->set(array('value'=>$value))->where("varname='{$varname}'")->execute();
        }else{
            $data = array(
                'webid'   => 0,
                'varname' => $varname,
                'value'   => $value,
            );
            DB::insert('sysconfig',array_keys($data))->values(array_values($data))->execute();
        }
    }

    /**
     * 优惠策略列表
     */
    public function action_discount_strategy()
    {
        $action = $this->params['action'];
        if(empty($action)){
            $this->display('stourtravel/ebooking/discount/list');
        }else if ($action=='read'){
            $data = array(
                'start'   => Common::remove_xss(Arr::get($_GET, 'start')),
                'limit'   => Common::remove_xss(Arr::get($_GET, 'limit')),
                'keyword' => Common::remove_xss(Arr::get($_GET, 'keyword')),
                'sort'    => Common::remove_xss(Arr::get($_GET, 'sort')),
                'type'    => Common::remove_xss(Arr::get($_GET, 'strategy_type')),
            );
            $list = Model_Ebooking_Discount_Strategy::get_list($data);

            $result['total'] = $list['total'];
            $result['lists'] = $list['list'];
            $result['success'] = true;
            echo json_encode($result);
        }elseif($action=='update'){
            $id = Common::remove_xss(Arr::get($_POST, 'id'));
            $field = Common::remove_xss(Arr::get($_POST, 'field'));
            $val = Common::remove_xss(Arr::get($_POST, 'val'));
            DB::update('discount_strategy')->set(array($field=>$val))->where('id','=',$id)->execute();
            echo 'ok';
        }elseif($action=='delete'){
            $rawdata = file_get_contents('php://input');
            $data = json_decode($rawdata);
            $id = $data->id;
            DB::update('discount_strategy')->set(array('is_delete'=>1))->where('id','=',$id)->execute();
        }
    }

    /**
     * 添加或编辑策略
     */
    public function action_discount_add_or_edit()
    {
        $id = $this->params['id'];
        if($id){
            $info = DB::select()->from('discount_strategy')->where("id={$id}")->execute()->current();
            $info['parameter'] = json_decode($info['parameter'],true);
            if($info['strategy_type']==1){
                if($info['parameter']['discount_type']==1){
                    $info['parameter']['room_number_1'] = $info['parameter']['room_number'];
                    $info['parameter']['discount_ratio'] = bcmul($info['parameter']['discount'],100);
                }else{
                    $info['parameter']['discount_price'] = $info['parameter']['discount'];
                }
            }else{
                $info['parameter']['room_number_2'] = $info['parameter']['room_number'];
            }
            $this->assign('info',$info);
        }
        $this->display('stourtravel/ebooking/discount/edit');
    }

    /**
     * @throws Kohana_Exception
     * 保存策略
     */
    public function action_ajax_save_discount()
    {
        $id = Common::remove_xss(Arr::get($_POST, 'id'));
        $data = array(
            'name'          => Common::remove_xss(Arr::get($_POST, 'name')),
            'strategy_type' => Common::remove_xss(Arr::get($_POST, 'strategy_type')),
            'is_open'       => Common::remove_xss(Arr::get($_POST, 'is_open')),
        );
        if($data['strategy_type']==1){
            $advance_day = Common::remove_xss(Arr::get($_POST, 'advance_day'));//提前天数
            $live_day    = Common::remove_xss(Arr::get($_POST, 'live_day'));//连住天数
            $room_number = Common::remove_xss(Arr::get($_POST, 'room_number_1'));
            if(!$live_day){
                exit(json_encode(array('status'=>false,'msg'=>'连住天数必填！')));
            }
            $discount_type = Common::remove_xss(Arr::get($_POST, 'discount_type'));
            $discount = $discount_type==1?Common::remove_xss(Arr::get($_POST, 'discount_ratio')):Common::remove_xss(Arr::get($_POST, 'discount_price'));
            if(!$discount){
                $msg = $discount_type==1?'请填写打几折':'请填写减免几元';
                exit(json_encode(array('status'=>false,'msg'=>$msg)));
            }
            $discount = $discount_type==1?bcdiv($discount,100,2):$discount;
            $data['parameter'] = json_encode(array(
                'advance_day'   => $advance_day,
                'live_day'      => $live_day,
                'room_number'   => $room_number,
                'discount_type' => $discount_type,
                'discount'      => $discount
            ));
        }else{
            $room_number     = Common::remove_xss(Arr::get($_POST, 'room_number_2'));
            $discount_number = Common::remove_xss(Arr::get($_POST, 'discount_number'));
            if(!$room_number || !$discount_number){
                exit(json_encode(array('status'=>false,'msg'=>'请填写完整的量返条件')));
            }
            $data['parameter'] = json_encode(array(
                'room_number'     => $room_number,
                'discount_number' => $discount_number
            ));
        }

        if($id){
            $data['modtime'] = time();
            DB::update('discount_strategy')->set($data)->where('id','=',$id)->execute();
        }else{
            $data['addtime'] = time();
            $data['modtime'] = time();
            $res = DB::insert('discount_strategy', array_keys($data))->values(array_values($data))->execute();
            $id = $res[0];
        }
        echo json_encode(array('status'=>true,'id'=>$id));
    }

    /**
     * 销售策略列表页
     */
    public function action_sale()
    {
        $action = $this->params['action'];
        if(empty($action)){
            $this->display('stourtravel/ebooking/sale/list');
        }else if ($action=='read'){
            $data = array(
                'start'   => Common::remove_xss(Arr::get($_GET, 'start')),
                'limit'   => Common::remove_xss(Arr::get($_GET, 'limit')),
                'keyword' => Common::remove_xss(Arr::get($_GET, 'keyword')),
                'sort'    => Common::remove_xss(Arr::get($_GET, 'sort')),
            );

            $sale_list = Model_Ebooking_Sale_Sale::get_list($this->type_id,$data);
            $result['total'] = $sale_list['total'];
            $result['lists'] = $sale_list['list'];
            $result['success'] = true;
            echo json_encode($result);
        }else if($action=='update'){
            $id = Common::remove_xss(Arr::get($_POST, 'id'));
            $field = Common::remove_xss(Arr::get($_POST, 'field'));
            $val = Common::remove_xss(Arr::get($_POST, 'val'));
            DB::update('sale_strategy')->set(array($field=>$val))->where('id','=',$id)->execute();
            echo 'ok';
        }else if($action=='delete'){
            $rawdata = file_get_contents('php://input');
            $data = json_decode($rawdata);
            $id = $data->id;
            DB::update('sale_strategy')->set(array('is_delete'=>1))->where('id','=',$id)->execute();
        }
    }

    /**
     * 新增销售策略
     */
    public function action_sale_add()
    {
        $this->assign('type_id',$this->type_id);
        $this->display('stourtravel/ebooking/sale/edit');
    }

    /**
     * 新增销售策略
     */
    public function action_sale_edit()
    {
        $id = $this->params['id'];
        $info = DB::select()->from('sale_strategy')->where('id','=',$id)->execute()->current();
        if($info['value_type']==1){
            $info['value'] = bcmul($info['value'],100);
        }

        $this->assign('type_id',$this->type_id);
        $this->assign('info',$info);
        $this->display('stourtravel/ebooking/sale/edit');
    }

    /**
     * @throws Kohana_Exception
     * 保存销售策略
     */
    public function action_ajax_sale_save_sale()
    {
        $id = Common::remove_xss(Arr::get($_POST, 'id'));
        $data = array(
            'name'       => Common::remove_xss(Arr::get($_POST, 'name')),
            'type'       => Common::remove_xss(Arr::get($_POST, 'type')),
            'value_type' => Common::remove_xss(Arr::get($_POST, 'value_type')),
            'value'      => Common::remove_xss(Arr::get($_POST, 'value')),
            'is_open'    => Common::remove_xss(Arr::get($_POST, 'is_open')),
            'type_id'    => Common::remove_xss(Arr::get($_POST, 'type_id')),
        );
        if($data['value_type']==1 && ($data['value']<1 || $data['value']>100)){
            exit(json_encode(array('status'=>false,'msg'=>'请输入1-100的百分比')));
        }
        if($data['value_type']==2 && ($data['value']<0.01 || !$data['value'])){
            exit(json_encode(array('status'=>false,'msg'=>'请输入大于0的金额')));
        }
        $data['value'] = $data['value_type']==1?bcdiv($data['value'],100,2):$data['value'];
        if($id){
            DB::update('sale_strategy')->set($data)->where('id','=',$id)->execute();
        }else{
            $data['create_time'] = time();
            $res = DB::insert('sale_strategy', array_keys($data))->values(array_values($data))->execute();
            $id = $res[0];
        }

        echo json_encode(array('status'=>true,'id'=>$id));
    }

    public function action_dialog_set_discount()
    {
        $id = Common::remove_xss(Arr::get($_GET, 'id'));
        $type = Common::remove_xss(Arr::get($_GET, 'type'));
        if(strstr($id,'"')){
            $id = implode(',',json_decode($id,true));
        }else{
            if(strstr($id,'suit')){
                $room_id = explode('_',$id);
                $purchaser_id_str = DB::select()->from('hotel_discount_strategy')->where("room_id={$room_id[1]}")->execute()->get('purchaser_id_str');
                $this->assign('status',$purchaser_id_str?1:2);
            }else{
                $purchaser_id_str = DB::select()->from('hotel_discount_strategy')->where("hotel_id={$id} and room_id<1")->execute()->get('purchaser_id_str');
                $this->assign('status',$purchaser_id_str?1:2);
            }
        }
        $this->assign('id',$id);
        $this->assign('type',$type);
        $this->display('stourtravel/ebooking/discount/set_discount');
    }

    public function action_ajax_get_discount_list()
    {
        $data = array(
            'start'   => Common::remove_xss(Arr::get($_GET, 'start')),
            'limit'   => Common::remove_xss(Arr::get($_GET, 'limit')),
            'keyword' => Common::remove_xss(Arr::get($_GET, 'keyword')),
            'id'      => Common::remove_xss(Arr::get($_GET, 'id')),
            'type'    => Common::remove_xss(Arr::get($_GET, 'type')),
        );
        $data['type'] = strstr($data['id'],'suit')?1:2;
        $list = Model_Ebooking_Discount_Strategy::get_list($data);

        $result['total'] = $list['total'];
        $result['lists'] = $list['list'];
        $result['success'] = true;
        echo json_encode($result);
    }

    /**
     * 酒店或房型绑定优惠策略
     */
    public function action_ajax_hotel_relation_discount()
    {
        $hotelOrRoomId = Common::remove_xss(Arr::get($_POST, 'hotelOrRoomId'));
        $discount_id = Common::remove_xss(Arr::get($_POST, 'id'));
        $purchaser_id = Common::remove_xss(Arr::get($_POST, 'purchaser_id'));
        if(!$hotelOrRoomId || !$discount_id){
            $msg = $hotelOrRoomId?'请选择策略':'请选择酒店或房型';
            exit(json_encode(array('status'=>false,'msg'=>$msg)));
        }
        $type = 2;
        if(strstr($hotelOrRoomId,',')){
            $hotelOrRoomId = explode(',',$hotelOrRoomId);
            foreach ($hotelOrRoomId as $v){
                if(strstr($v,'suit')){
                    $id = explode('_',$v);
                    $id = $id[1];
                    $type = 1;
                }else{
                    $id = $v;
                }
                self::update_hotel_discount_strategy($discount_id,$purchaser_id,$id,$type);
            }
        }else{
            if(strstr($hotelOrRoomId,'suit')){
                $hotelOrRoomId = explode('_',$hotelOrRoomId);
                $hotelOrRoomId = $hotelOrRoomId[1];
                $type = 1;
            }
            self::update_hotel_discount_strategy($discount_id,$purchaser_id,$hotelOrRoomId,$type);
        }

        echo json_encode(array('status'=>true));
    }

    /**
     * @param $discount_id
     * @param $purchaser_id
     * @param $hotelOrRoomId
     * @param $type
     * @throws Kohana_Exception
     * 修改策略关联信息
     */
    public function update_hotel_discount_strategy($discount_id,$purchaser_id,$hotelOrRoomId,$type)
    {
        if($type==1){
            $room_info = DB::select()->from('hotel_room')->where("id={$hotelOrRoomId}")->execute()->current();
            $data = array(
                'hotel_id' => $room_info['hotelid'],
                'room_id'  => $room_info['id'],
            );
            $sql = "hotel_id={$room_info['hotelid']} and room_id={$room_info['id']}";
        }else{
            $data = array(
                'hotel_id' => $hotelOrRoomId,
                'room_id'  => 0,
            );
            $sql = "hotel_id={$hotelOrRoomId} and room_id<1";
        }
        $data['discount_id'] = $discount_id;
        $data['purchaser_id_str'] = $purchaser_id;
        $is_exist = DB::select()->from('hotel_discount_strategy')->where($sql)->execute()->current();
        if($is_exist){
            DB::update('hotel_discount_strategy')->set($data)->where('id','=',$is_exist['id'])->execute();
        }else{
            DB::insert('hotel_discount_strategy', array_keys($data))->values(array_values($data))->execute();
        }
    }

    public function action_dialog_set_sale()
    {
        $id = Common::remove_xss(Arr::get($_GET, 'id'));
        if(strstr($id,'"')){
            $id = implode(',',json_decode($id,true));
        }else{
            $room_id = explode('_',$id);
            $purchaser_id_str = DB::select()->from('hotel_sale_strategy')->where("room_id={$room_id[1]}")->execute()->get('purchaser_id_str');
            $this->assign('status',$purchaser_id_str?1:2);
        }
        $this->assign('id',$id);
        $this->display('stourtravel/ebooking/sale/set_sale');
    }

    public function action_ajax_get_sale_list()
    {
        $data = array(
            'start'   => Common::remove_xss(Arr::get($_GET, 'start')),
            'limit'   => Common::remove_xss(Arr::get($_GET, 'limit')),
            'keyword' => Common::remove_xss(Arr::get($_GET, 'keyword')),
            'room_id' => Common::remove_xss(Arr::get($_GET, 'room_id')),
        );
        $sale_list = Model_Ebooking_Sale_Sale::get_list($this->type_id,$data);

        $result['total'] = $sale_list['total'];
        $result['lists'] = $sale_list['list'];
        $result['success'] = true;
        echo json_encode($result);
    }

    public function action_ajax_hotel_relation_sale()
    {
        $room_id = Common::remove_xss(Arr::get($_POST, 'roomid'));
        $sale_id = Common::remove_xss(Arr::get($_POST, 'id'));
        $purchaser_id = Common::remove_xss(Arr::get($_POST, 'purchaser_id'));
        if(!$room_id || !$sale_id){
            $msg = $room_id?'请选择策略':'请选择酒店';
            exit(json_encode(array('status'=>false,'msg'=>$msg)));
        }
        if(strstr($room_id,',')){
            $room_id = explode(',',$room_id);
            foreach ($room_id as $v){
                $id = explode('_',$v);
                self::update_hotel_sale_strategy($sale_id,$purchaser_id,$id);
            }
        }else{
            $room_id = explode('_',$room_id);
            self::update_hotel_sale_strategy($sale_id,$purchaser_id,$room_id);
        }

        echo json_encode(array('status'=>true));
    }

    /**
     * @param $sale_id
     * @param $purchaser_id
     * @param $room_id
     * @throws Kohana_Exception
     * 修改或插入酒店与销售策略的关联
     */
    public function update_hotel_sale_strategy($sale_id,$purchaser_id,$room_id)
    {
        $room_info = DB::select()->from('hotel_room')->where("id={$room_id[1]}")->execute()->current();
        $data = array(
            'hotel_id' => $room_info['hotelid'],
            'room_id'  => $room_info['id'],
            'sale_id'  => $sale_id,
            'purchaser_id_str' => $purchaser_id
        );
        $is_exist = DB::select()->from('hotel_sale_strategy')->where("hotel_id={$room_info['hotelid']} and room_id={$room_info['id']}")->execute()->current();
        if($is_exist){
            DB::update('hotel_sale_strategy')->set($data)->where('id','=',$is_exist['id'])->execute();
        }else{
            DB::insert('hotel_sale_strategy', array_keys($data))->values(array_values($data))->execute();
        }
    }

    /**
     * 删除关联策略
     */
    public function action_ajax_delete_strategy()
    {
        $id = Arr::get($_POST,'id');
        $type = Arr::get($_POST,'type');
        if($type==1){
            if(strstr($id,'suit')){
                $arr = explode('_',$id);
                $id = $arr[1];
                DB::delete('hotel_discount_strategy')->where("room_id={$id}")->execute();
            }else{
                DB::delete('hotel_discount_strategy')->where("hotel_id={$id} and room_id=0")->execute();
            }

        }else{
            $arr = explode('_',$id);
            $id = $arr[1];
            DB::delete('hotel_sale_strategy')->where("room_id={$id}")->execute();
        }
        echo 1;
    }

    public function action_finance()
    {
        $action = $this->params['action'];
        if(empty($action)){
            $this->display('stourtravel/ebooking/finance/list');
        }elseif($action=='read'){
            $start = Arr::get($_GET,'start');
            $limit = Arr::get($_GET,'limit');
            $keyword = Arr::get($_GET,'keyword');
            $start_time = Arr::get($_GET,'start_time');
            $end_time = Arr::get($_GET,'end_time');
            $status = Arr::get($_GET,'status');

            $sql = "SELECT b.*,a.ordersn,a.productname,a.paytime,a.addtime,a.status FROM sline_member_order AS a ";
            $sql.= "LEFT JOIN sline_member_order_compute AS b ON(a.id=b.order_id) ";
            $sql.= "WHERE a.channel_id=3 ";
            if($keyword){
                $sql.= "AND (a.productname LIKE '%{$keyword}%' OR a.ordersn='{$keyword}' OR a.linkman='{$keyword}' OR a.linktel='{$keyword}') ";
            }
            if($status && $status<99){
                $sql.= "AND a.status={$status} ";
            }
            if($start_time && $end_time){
                $start_time = strtotime($start_time);
                $end_time = strtotime($end_time);
                $sql.= "AND a.paytime>={$start_time} AND a.paytime<={$end_time} ";
            }
            $sql.= "ORDER BY a.paytime DESC,a.addtime DESC ";
            $total = DB::query(1, $sql)->execute()->count();
            $sql.= "LIMIT {$start},{$limit} ";
            $list = DB::query(1, $sql)->execute()->as_array();
            foreach ($list as &$v){
                $v['paytime'] = $v['paytime']?date('Y-m-d H:i:s',$v['paytime']):date('Y-m-d H:i:s',$v['addtime']);
                $v['status_name'] = $v['status']==2?'待消费':'已完成';
            }

            $result['total'] = $total;
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
    }
}